package com.shf.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.shf.lease.entity.*;
import com.shf.lease.enums.ItemType;
import com.shf.lease.enums.LeaseStatus;
import com.shf.lease.exception.BizException;
import com.shf.lease.result.Result;
import com.shf.lease.result.ResultCodeEnum;
import com.shf.lease.web.admin.controller.apartment.query.QueryRoomParams;
import com.shf.lease.web.admin.controller.apartment.request.RoomSubmitVo;
import com.shf.lease.web.admin.controller.apartment.response.GraphVo;
import com.shf.lease.web.admin.controller.apartment.response.PageListVo;
import com.shf.lease.web.admin.controller.apartment.response.RoomVo;
import com.shf.lease.web.admin.mapper.ApartmentInfoMapper;
import com.shf.lease.web.admin.service.*;
import com.shf.lease.web.admin.mapper.RoomInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* @author 叶枫
* @description 针对表【room_info(房间信息表)】的数据库操作Service实现
* @createDate 2024-07-05 18:06:52
*/
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
    implements RoomInfoService {


    @Resource
    private ApartmentInfoMapper apartmentInfoMapper;
    @Resource
    private LeaseAgreementService leaseAgreementService;

    @Resource
    private GraphInfoService graphInfoService;
    @Resource
    private RoomAttrValueService roomAttrValueService;
    @Resource
    private RoomFacilityService roomFacilityService;
    @Resource
    private RoomLabelService roomLabelService;
    @Resource
    private RoomLeaseTermService roomLeaseTermService;
    @Resource
    private RoomPaymentTypeService roomPaymentTypeService;

    @Override
    public Result<PageListVo<RoomVo>> queryPageListRoom(QueryRoomParams queryParams) {
        PageListVo<RoomVo> pageListVo = new PageListVo<>();
        //查询符合条件的房间
        Page<RoomInfo> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        Page<RoomInfo> roomInfoPage = this.page(page);

        //查询符合条件的公寓
        Long provinceId = queryParams.getProvinceId();
        Long districtId = queryParams.getDistrictId();
        Long cityId = queryParams.getCityId();
        Long apartmentId = queryParams.getApartmentId();
        LambdaQueryWrapper<ApartmentInfo> apartmentWrapper = new LambdaQueryWrapper<>();
        apartmentWrapper.eq(provinceId != null, ApartmentInfo::getProvinceId, provinceId)
                .eq(districtId != null, ApartmentInfo::getDistrictId, districtId)
                .eq(cityId != null, ApartmentInfo::getCityId, cityId)
                .eq(apartmentId != null, ApartmentInfo::getId, apartmentId);
        List<ApartmentInfo> apartmentInfos = apartmentInfoMapper.selectList(apartmentWrapper);
        Map<Long, ApartmentInfo> apartmentInfoMap = apartmentInfos.stream().collect(Collectors.toMap(ApartmentInfo::getId, Function.identity()));
        List<RoomVo> RoomVoList = roomInfoPage.getRecords().stream().map(roomInfo -> {
            RoomVo roomVo = new RoomVo();
            roomVo.setId(roomInfo.getId());
            roomVo.setRoomNumber(roomInfo.getRoomNumber());
            roomVo.setRent(roomInfo.getRent());
            if (apartmentInfoMap.containsKey(roomInfo.getApartmentId())) {
                roomVo.setApartmentInfo(apartmentInfoMap.get(roomInfo.getApartmentId()));
            }
            return roomVo;
        }).collect(Collectors.toList());
        List<LeaseAgreement> leaseAgreements = leaseAgreementService.list();
        Map<String, LeaseAgreement> leaseAgreementMap = leaseAgreements.stream().collect(Collectors.toMap(leaseAgreement -> leaseAgreement.getRoomId().toString() + leaseAgreement.getApartmentId().toString(), Function.identity()));

        List<RoomVo> roomVoList = RoomVoList.stream().map(new Function<RoomVo, RoomVo>() {
                    @Override
                    public RoomVo apply(RoomVo roomVo) {
                        if (leaseAgreementMap.containsKey(roomVo.getId().toString() + roomVo.getApartmentInfo().getId().toString())) {
                            LeaseAgreement leaseAgreement = leaseAgreementMap.get(roomVo.getId().toString() + roomVo.getApartmentInfo().getId().toString());
                            if (leaseAgreement.getStatus().equals(LeaseStatus.SIGNED) || leaseAgreement.getStatus().equals(LeaseStatus.WITHDRAWING)) {
                                roomVo.setIsCheckIn(false);
                                roomVo.setLeaseEndDate(leaseAgreement.getLeaseEndDate());
                            } else {
                                roomVo.setIsCheckIn(true);
                            }

                        } else {
                            roomVo.setIsCheckIn(true);
                        }
                        return roomVo;
                    }
                }).skip((queryParams.getPageNum() - 1) * queryParams.getPageSize())
                .limit(queryParams.getPageSize()).collect(Collectors.toList());

        pageListVo.setRecourds(roomVoList);
        pageListVo.setPageSize(queryParams.getPageSize());
        pageListVo.setTotal((long) roomVoList.size());
        pageListVo.setPageNum(queryParams.getPageNum());
        return Result.ok(pageListVo);

    }

    @Override
    public void saveOrUpdateRoom(RoomSubmitVo roomSubmitVo) {
        boolean isUpdate = roomSubmitVo.getId() != null;
        super.saveOrUpdate(roomSubmitVo);

        //若为更新操作，则先删除与Room相关的各项信息列表
        if (isUpdate) {
            //1.删除原有graphInfoList
            LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
            graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
            graphQueryWrapper.eq(GraphInfo::getItemId, roomSubmitVo.getId());
            graphInfoService.remove(graphQueryWrapper);

            //2.删除原有roomAttrValueList
            LambdaQueryWrapper<RoomAttrValue> attrQueryMapper = new LambdaQueryWrapper<>();
            attrQueryMapper.eq(RoomAttrValue::getRoomId, roomSubmitVo.getId());
            roomAttrValueService.remove(attrQueryMapper);

            //3.删除原有roomFacilityList
            LambdaQueryWrapper<RoomFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
            facilityQueryWrapper.eq(RoomFacility::getRoomId, roomSubmitVo.getId());
            roomFacilityService.remove(facilityQueryWrapper);

            //4.删除原有roomLabelList
            LambdaQueryWrapper<RoomLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
            labelQueryWrapper.eq(RoomLabel::getRoomId, roomSubmitVo.getId());
            roomLabelService.remove(labelQueryWrapper);

            //5.删除原有paymentTypeList
            LambdaQueryWrapper<RoomPaymentType> paymentQueryWrapper = new LambdaQueryWrapper<>();
            paymentQueryWrapper.eq(RoomPaymentType::getRoomId, roomSubmitVo.getId());
            roomPaymentTypeService.remove(paymentQueryWrapper);


            //6.删除原有leaseTermList
            LambdaQueryWrapper<RoomLeaseTerm> termQueryWrapper = new LambdaQueryWrapper<>();
            termQueryWrapper.eq(RoomLeaseTerm::getRoomId, roomSubmitVo.getId());
            roomLeaseTermService.remove(termQueryWrapper);
        }

        //1.保存新的graphInfoList
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemType(ItemType.ROOM);
                graphInfo.setItemId(roomSubmitVo.getId());
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

        //2.保存新的roomAttrValueList
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIds)) {
            List<RoomAttrValue> roomAttrValueList = new ArrayList<>();
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue roomAttrValue = RoomAttrValue.builder().roomId(roomSubmitVo.getId()).attrValueId(attrValueId).build();
                roomAttrValueList.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValueList);
        }

        //3.保存新的facilityInfoList
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<RoomFacility> roomFacilityList = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = RoomFacility.builder().roomId(roomSubmitVo.getId()).facilityId(facilityInfoId).build();
                roomFacilityList.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilityList);
        }

        //4.保存新的labelInfoList
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIds)) {
            ArrayList<RoomLabel> roomLabelList = new ArrayList<>();
            for (Long labelInfoId : labelInfoIds) {
                RoomLabel roomLabel = RoomLabel.builder().roomId(roomSubmitVo.getId()).labelId(labelInfoId).build();
                roomLabelList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelList);
        }

        //5.保存新的paymentTypeList
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIds)) {
            ArrayList<RoomPaymentType> roomPaymentTypeList = new ArrayList<>();
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder().roomId(roomSubmitVo.getId()).paymentTypeId(paymentTypeId).build();
                roomPaymentTypeList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }

        //6.保存新的leaseTermList
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)) {
            ArrayList<RoomLeaseTerm> roomLeaseTerms = new ArrayList<>();
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder().roomId(roomSubmitVo.getId()).leaseTermId(leaseTermId).build();
                roomLeaseTerms.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTerms);
        }
    }

    @Override
    public void removeRoomById(Long id) {
        //1.删除RoomInfo
        super.removeById(id);

        //2.删除graphInfoList
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        graphQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphQueryWrapper);

        //3.删除attrValueList
        LambdaQueryWrapper<RoomAttrValue> attrQueryWrapper = new LambdaQueryWrapper<>();
        attrQueryWrapper.eq(RoomAttrValue::getRoomId, id);
        roomAttrValueService.remove(attrQueryWrapper);

        //4.删除facilityInfoList
        LambdaQueryWrapper<RoomFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(RoomFacility::getRoomId, id);
        roomFacilityService.remove(facilityQueryWrapper);

        //5.删除labelInfoList
        LambdaQueryWrapper<RoomLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(RoomLabel::getRoomId, id);
        roomLabelService.remove(labelQueryWrapper);

        //6.删除paymentTypeList
        LambdaQueryWrapper<RoomPaymentType> paymentQueryWrapper = new LambdaQueryWrapper<>();
        paymentQueryWrapper.eq(RoomPaymentType::getRoomId, id);
        roomPaymentTypeService.remove(paymentQueryWrapper);

        //7.删除leaseTermList
        LambdaQueryWrapper<RoomLeaseTerm> termQueryWrapper = new LambdaQueryWrapper<>();
        termQueryWrapper.eq(RoomLeaseTerm::getRoomId, id);
        roomLeaseTermService.remove(termQueryWrapper);
    }


}




